﻿#include "widget.h"
#include "ui_widget.h"
#include "qevent.h"
#include "qdebug.h"
#include "QList"
#include <QtCore/QList>
#include "SqliteOperator.h"
#include "timeDialog.h"
#include "frmmsg.h"
#include <QStandardItemModel>
#include "FsGlobal.h"
#include <vector>
#include "dialogset.h"
#include <QMessageBox>
#include <QMenu>



QList<TaskMain> taskMainList;

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);//去掉标题栏
//    this->setAttribute(Qt::WA_TranslucentBackground, true);//设置窗口背景透明

//    this->setAttribute(Qt::WA_TranslucentBackground);
//    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
    ui->titleFrame->installEventFilter(this);



    timer = new QTimer;
    connect(timer,&QTimer::timeout,this,&Widget::showTime);   // 信号连接 每一秒执行一次槽函数
    timer->start(100);


    checkTaskTimer = new QTimer;
    connect(checkTaskTimer,&QTimer::timeout,this,&Widget::checkTask);   // 信号连接 每一秒执行一次槽函数
    checkTaskTimer->start(1000);


//创建并打开SQLite数据库
    SqliteOperator sqlOper;
    sqlOper.openDb();



    // 判断数据表是否存在
    QString str1 = QString("task_main");
    if(!sqlOper.isTableExist(str1))
    {
        // 创建数据表
        sqlOper.createTable();
    }
//    qDebug() << "isTabelExist：" <<;

     sqlOper.closeDb();

    loadTaskList();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::loadTaskList(){
    QDateTime timedata = QDateTime::currentDateTime();   //  获取当前时间
//    string = Timedata.toString("yyyy-MM-dd hh:mm:ss");   //  设置显示格式
    long long nowTimeL = timedata.time().hour()*60*60 + timedata.time().minute()*60 + timedata.time().second();

    taskMainList.clear();
    SqliteOperator sqlOper;
    sqlOper.openDb();
    sqlOper.queryTable(taskMainList);
    qDebug() << "taskMainList";
    sort();
    QStandardItemModel* model = new QStandardItemModel(this);
    /*设置列字段名*/
    model->setColumnCount(3);
    model->setHeaderData(0,Qt::Horizontal, "ID");
    model->setHeaderData(1,Qt::Horizontal, "定时关机计划");
    model->setHeaderData(2,Qt::Horizontal, "下次执行计划");
//    model->setHeaderData(3,Qt::Horizontal, "是否启用");
    int rowIndex=0;
    foreach(TaskMain ent ,taskMainList){
        QString taskTimeStr =QString::number(ent.taskTime/3600) +":"+ QString::number(ent.taskTime/60%60);
        int intervalType = ent.intervalType;
        QString intervalTypeStr ;
        switch (intervalType) {
        case 1:
            intervalTypeStr="执行一次";
            break;
        case 2:
            intervalTypeStr="每天";
            break;
        default:
            break;
        }
        QString idStr = QString::number(ent.id);
        model->setItem(rowIndex, 0, new QStandardItem(idStr));
        model->setItem(rowIndex, 1, new QStandardItem(taskTimeStr+"("+intervalTypeStr+")"));
        QString nextTaskStr="";
        if(intervalType==2){
            if(nowTimeL<ent.taskTime)
            {
                //                QDateTime::
                ent.nextTime=  timedata;
                QTime qtime;
                qtime.setHMS(ent.taskTime/3600,ent.taskTime/60%60,0);
                ent.nextTime.setTime(qtime);
                nextTaskStr = ent.nextTime.toString("yyyy-MM-dd HH:mm:ss");
//                nextTaskStr +=" "+ QString::number(ent.taskTime/3600) +":"+ QString::number(ent.taskTime/60%60);
            }
            else{
                ent.nextTime=  timedata.addDays(1);
                QTime qtime;
                qtime.setHMS(ent.taskTime/3600,ent.taskTime/60%60,0);
                ent.nextTime.setTime(qtime);
                nextTaskStr = ent.nextTime.toString("yyyy-MM-dd HH:mm:ss");
            }
        }
        model->setItem(rowIndex, 2, new QStandardItem(nextTaskStr));
//        QStandardItem *item = new QStandardItem();
//        item->setCheckable(true);
//        item->setCheckState(Qt::Checked);
//        model->setItem(rowIndex, 3, item);

        rowIndex++;
    }
    sqlOper.closeDb();

    ui->tableView->setModel(model);
    ui->tableView->setColumnHidden(0,true);
    //设置选中时为整行选中
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置表格的单元为只读属性，即不能编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setColumnWidth(0,20);
    ui->tableView->setColumnWidth(1,200);
    ui->tableView->setColumnWidth(2,200);
}


bool Widget::eventFilter(QObject *watched, QEvent *evt)
{
    static int index = 1;
    static QPoint mousePoint;
    static bool mousePressed = false;

    QMouseEvent *event = static_cast<QMouseEvent *>(evt);
    if (event->type() == QEvent::MouseButtonPress) {
        if (event->button() == Qt::LeftButton) {
            mousePressed = true;
            mousePoint = event->globalPos() - this->pos();

//            if (index == 5) {
//                index = 1;
//            } else {
//                index++;
//            }
//
//               ui->frame->setStyleSheet(QString("background-image:url(:/image/%1.png);").arg(index));

            return true;
        } else {
//            exit(0);
        }
    } else if (event->type() == QEvent::MouseButtonRelease) {
        mousePressed = false;
        return true;
    } else if (event->type() == QEvent::MouseMove) {
        if (mousePressed && (event->buttons() && Qt::LeftButton)) {
            this->move(event->globalPos() - mousePoint);
            return true;
        }
    }

    return QWidget::eventFilter(watched, event);
}

void Widget::on_closeTBtn_clicked()
{
    if( QMessageBox::question(this, "提示", "退出程序后不能实现自动关机，确定退出吗?", QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes)
    {
         exit(0);
    }
}


void Widget::showTime()
{
    QString string;
    QDateTime Timedata = QDateTime::currentDateTime();   //  获取当前时间
    string = Timedata.toString("yyyy-MM-dd hh:mm:ss");   //  设置显示格式
    ui-> timeLbl->setText(string);  // 设置标签内容
}


void Widget::on_ShutdownPBtn_clicked()
{
    TimeDialog *timeDialog = new TimeDialog();
    connect(timeDialog,SIGNAL(ExitWin()),this,SLOT(loadTaskList()));
    timeDialog->exec();

}


void Widget::on_minTBtn_clicked()
{
//      setWindowState(Qt::WindowMinimized);
// 最小化到后台
    this->hide();

    m_pSystemTray = new QSystemTrayIcon();
    m_pSystemTray->setIcon(QIcon(":/image/shutdown.ico"));     // 托盘时显示的图片
    m_pSystemTray->setToolTip("定时关机");
    //给QSystemTrayIcon添加槽函数
    connect(m_pSystemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
    //建立托盘操作的菜单
    CreatAction();
    CreatMenu();

    m_pSystemTray->show();
}

void Widget::CreatAction()
{
    m_pActionShow = new QAction("显示主界面", this);
    connect(m_pActionShow, SIGNAL(triggered()), this, SLOT(slotActionMain()));

    m_pActionQuit = new QAction("退出", this);
    connect(m_pActionQuit, SIGNAL(triggered()), this, SLOT(slotActionExitApp()));

}

void Widget::CreatMenu()
{
    m_pTrayMennu = new QMenu(this);
    //新增菜单项---显示主界面
    m_pTrayMennu->addAction(m_pActionShow);
    //增加分隔符
    m_pTrayMennu->addSeparator();
    //新增菜单项---退出程序
    m_pTrayMennu->addAction(m_pActionQuit);
    //把QMenu赋给QSystemTrayIcon对象
    m_pSystemTray->setContextMenu(m_pTrayMennu);
}

void Widget::slotActionMain()
{
    this->show();
    m_pSystemTray->hide();
}

void Widget::slotActionExitApp()
{
    if( QMessageBox::question(this, "提示", "退出程序后不能实现自动关机，确定退出吗?", QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes)
    {
            exit(0);
    }

}

void Widget::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::Trigger:
    //单击托盘图标
        //        m_pSystemTray->showMessage("提示",
        //                                    "自动关机小程序",
        //                                    QSystemTrayIcon::Information,
        //                                    1000);
        this->show();
        m_pSystemTray->hide();
        break;
    case QSystemTrayIcon::DoubleClick:
        //双击托盘图标
        //双击后显示主程序窗口
        this->show();
        m_pSystemTray->hide();
        break;
    default:
        break;
    }
}


void Widget::on_delPBtn_clicked()
{
    int row=  ui->tableView->currentIndex().row();
    QAbstractItemModel *model1 = ui->tableView->model();
    qDebug()<< model1->index(row,0).data().toInt();
    SqliteOperator sqlOper;
    sqlOper.openDb();
    sqlOper. deleteData(model1->index(row,0).data().toInt());
    sqlOper.closeDb();
    model1->removeRow(row);

}


void Widget::on_setTBtn_clicked()
{
    DialogSet *dialogSet = new DialogSet();
    dialogSet->exec();
}


//检查关机时间，每秒执行一次
void Widget::checkTask(){
    QString string;
    QDateTime Timedata = QDateTime::currentDateTime();   //  获取当前时间
    string = Timedata.toString("yyyy-MM-dd hh:mm:ss");   //  设置显示格式
    long long nowTimeL = Timedata.time().hour()*60*60 + Timedata.time().minute()*60 + Timedata.time().second();

    long long nextTimeL=-1;
    int i=0;
    for(i=0;i<taskMainList.size();i++)
    {
        if(taskMainList[i].taskTime>nowTimeL){
            nextTimeL = taskMainList[i].taskTime;
            mode=taskMainList[i].mode;
            break;
        }
    }
    if(taskMainList.size()>0){

        QString taskTimeStr ;
        if(nextTimeL>=0)
        {
            taskTimeStr="今天 ";

        }
        else
        {
            nextTimeL = taskMainList[0].taskTime;
            mode=taskMainList[0].mode;
             taskTimeStr="明天 ";
        }
        taskTimeStr +=QString::number(nextTimeL/3600) +"时"+ QString::number(nextTimeL/60%60)+"分";
        if(mode==1){
            taskTimeStr+="(关机)";
        }
        else if (mode ==2){
            taskTimeStr+="(睡眠)";
        }

        ui->taskTimeLbl->setText(taskTimeStr);
    }


    if(nextTimeL-nowTimeL== 120)
    {
        countdownMain=nextTimeL -nowTimeL;
        countdownMain=120;
    }
    if(countdownMain ==120){
        FrmMsg *frmMsg = new FrmMsg();
        frmMsg->show();
    }
    if(countdownMain>=0){
        countdownMain--;
    }
     if (countdownMain==0){

            switch (mode) {
            case 1:
                qDebug() << "执行关机";
                system("shutdown -s -t 00");
                break;
            case 2:
                qDebug() << "执行睡眠";
                system("rundll32.exe powrprof.dll, SetSuspendState 睡眠");
                break;
            default:
                break;
            }

    }

}



//static bool compareTaskData(const TaskMain &taskMain1, const TaskMain &taskMain2){
//    return taskMain1.taskTime>taskMain2.taskTime;
//}





void Widget::on_soonBtn_clicked()
{
    qDebug() << "执行睡眠";
    system("rundll32.exe powrprof.dll, SetSuspendState 睡眠");

}

//按定时的时间来排序
void Widget::sort(){
    int length=taskMainList.length();
    for(int i=0;i<length;i++){
            for(int j=0;j< length -1-i;j++){
                if(taskMainList[j].taskTime>taskMainList[j+1].taskTime){
                TaskMain tmp = taskMainList[j];
                taskMainList[j]=taskMainList[j+1];
                taskMainList[j+1]=tmp;
                }
            }
    }

}
